package com.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.MyApp;
import com.bean.AllListBean;
import com.bean.DataEvent;
import com.bean.HeadBean;
import com.bean.PackageBean;
import com.constant.Constant;
import com.constant.PackageType;
import com.custom.NoScrollViewPager;
import com.fragment.DynamicsFragment;
import com.fragment.HomeFragment;
import com.fragment.RechargeFragment;
import com.fragment.MineFragment;
import com.interfaces.IEvent;
import com.lottery.R;
import com.message.MsgId;
import com.socket.UnPacket;
import com.util.DataTypeUtil;
import com.util.JsonUtils;
import com.util.LogUtil;
import com.util.SocketTask;
import com.util.StatusBarUtil;
import com.util.ToastUtils;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class HomeActivity extends BaseActivity implements View.OnClickListener {

    private StringBuffer stringBuffer;
    private int CAPACITY = 1024;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(10240000);
    private int timesByteBuffer;
    //    private ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
    private int mLength;
    private boolean flag;
    private InputStream is;
    private OutputStream os;
    private String mJson;
    private Socket socket;
    private TabLayout mTabLayout;
    //Tab 文字
    private final int[] TAB_TITLES = new int[]{R.string.home, R.string.recharge, R.string.dynamics,
            R.string.mine};
    //Tab 图片
    private final int[] TAB_IMAGES = new int[]{R.drawable.tab_home_selector,
            R.drawable.tab_recharge_selector, R.drawable.tab_dynamics_selector,
            R.drawable.tab_mine_selector};
    //Titles
    private int[] TITLES = new int[]{R.string.title_app_name, R.string.title_recharge,
            R.string.title_dynamics, R.string.title_personal_center};

    private NoScrollViewPager mViewPager;
    private ImageView mImgMine;
    private TextView mTextRechargeRecord;
    private TextView mTitle;
    private PackageBean packageBean;
    private ArrayList<PackageBean> packageList;
    private boolean isStop;
    private byte[] bytesHead;
    private Fragment[] TAB_FRAGMENTS;
    private HomeFragment mHomeFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        StatusBarUtil.setColor(this);

        EventBus.getDefault().register(this);
        initData();
        initUI();
        setOnclick();
        new Thread(new Runnable() {

            @Override
            public void run() {
                initListData();
            }
        }).run();
    }

    private void initData() {
        mHomeFragment = new HomeFragment();
        RechargeFragment rechargeFragment = new RechargeFragment();
        DynamicsFragment dynamicsFragment = new DynamicsFragment();
        MineFragment serverFragment = new MineFragment();
        //Fragment 数组
        TAB_FRAGMENTS = new Fragment[]{mHomeFragment, rechargeFragment, dynamicsFragment, serverFragment};
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onDataSuccess(DataEvent dataEvent) {
        String str = dataEvent.getStr();
        if (!TextUtils.isEmpty(str)) {
            LogUtil.e("------" + str);
            AllListBean result = JsonUtils.getResult(str, AllListBean.class);
            List<AllListBean.DataBean> listLottery = result.getData();
            mHomeFragment.notifyDataChange(listLottery);
        }
    }

    private void setOnclick() {
        mImgMine = findViewById(R.id.btnMine);
        mImgMine.setOnClickListener(this);
        mTextRechargeRecord = findViewById(R.id.textRechargeRecord);
        mTextRechargeRecord.setOnClickListener(this);
        findViewById(R.id.btnService).setOnClickListener(this);
        mImgMine.setVisibility(View.VISIBLE);
    }

    private void initUI() {

        mTitle = findViewById(R.id.textTitle);

        mTabLayout = findViewById(R.id.tabLayout);
        setTabs(mTabLayout, TAB_IMAGES, TAB_TITLES);

        mViewPager = findViewById(R.id.viewPager);
        MyViewPagerAdapter pagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(pagerAdapter);

        mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
//        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                mTitle.setText(TITLES[position]);
                if (position == 0)
                    mImgMine.setVisibility(View.VISIBLE);
                else
                    mImgMine.setVisibility(View.GONE);
                if (position == 1)
                    mTextRechargeRecord.setVisibility(View.VISIBLE);
                else
                    mTextRechargeRecord.setVisibility(View.GONE);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 设置添加Tab
     *
     * @param tabLayout
     * @param tabImages
     * @param tabTitles
     */
    private void setTabs(TabLayout tabLayout, int[] tabImages, int[] tabTitles) {
        LayoutInflater inflater = getLayoutInflater();
        for (int i = 0; i < tabImages.length; i++) {

            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.tab_custom, null);
            tab.setCustomView(view);

            ImageView imgTab = view.findViewById(R.id.img_tab);
            imgTab.setImageResource(tabImages[i]);
            TextView tvTitle = view.findViewById(R.id.tv_tab);
            tvTitle.setText(tabTitles[i]);

            tabLayout.addTab(tab);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnMine:
                ToastUtils.showToast("ToDo");
                break;
            case R.id.textRechargeRecord:
                ToastUtils.showToast("ToDoRecharge");
                break;
            case R.id.btnService:
                ToastUtils.showToast("ToDoService");
                break;

        }
    }

    /**
     * @description: ViewPager 适配器
     */
    private class MyViewPagerAdapter extends FragmentPagerAdapter {
        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(final int position) {
            return TAB_FRAGMENTS[position];
        }

        @Override
        public int getCount() {
            return TAB_FRAGMENTS.length;
        }
    }

    private void initListData() {
        stringBuffer = new StringBuffer();
        packageList = new ArrayList<>();
        String encoder = DataTypeUtil.encoder("{}");
        MyAsync myAsync = new MyAsync(encoder);
        myAsync.execute("");

    }

    class MyAsync extends AsyncTask<String, Void, String> {

        private String encoder;

        public MyAsync(String encoder) {
            this.encoder = encoder;
        }

        @Override
        protected void onPostExecute(String s) {
            LogUtil.e(s);
            if (!TextUtils.isEmpty(s)) {
                AllListBean result = JsonUtils.getResult(s, AllListBean.class);
                List<AllListBean.DataBean> data = result.getData();
                AllListBean.DataBean dataBean = data.get(0);
                List<AllListBean.DataBean.LevelsBean> levels = dataBean.getLevels();
            }

        }

        @Override
        protected String doInBackground(String... strings) {
            String connect = connect(encoder);
            return connect;
        }


    }

    private String connect(String encoder) {
        String message = "";
        byteBuffer.order(ByteOrder.nativeOrder());
        try {
            socket = SocketTask.getInstance();
            if (socket.isConnected()) {
                os = SocketTask.getOS();
                is = SocketTask.getIS();
//                sendData(os, PackageType.GET_BANNER_LIST, (short) 0, encoder);
//                received(is);
                sendData(os, PackageType.GET_ALL_LIST, (short) 0, encoder);
                received(is);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        message = mJson;
        return message;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            // 退到后台
            moveTaskToBack(false);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void sendData(OutputStream os, short type, short msgId, String body) throws IOException {
        int length = 8 + body.length();
        byte[] msg = new byte[length];
        byte[] temp;
        temp = DataTypeUtil.short2byte((short) length);//长度
        System.arraycopy(temp, 0, msg, 0, 2);
        temp = DataTypeUtil.short2byte(Constant.TYPE_INSTRUCTION);//包的指令类型
        System.arraycopy(temp, 0, msg, 2, 2);
        temp = DataTypeUtil.short2byte(type);// 包类型
        System.arraycopy(temp, 0, msg, 4, 2);
        temp = DataTypeUtil.short2byte(msgId);// 包序号
        System.arraycopy(temp, 0, msg, 6, 2);
        temp = body.getBytes();
        System.arraycopy(temp, 0, msg, 8, body.length());
        os.write(msg, 0, msg.length);
    }

    private void received(InputStream is) throws IOException {
        handing(is);
//        newMethod(is);
//        handingData(packageList);
    }

    private DataInputStream dis;
    private byte[] head = new byte[8];
    private int headLen = 0;

    private void handing(InputStream is) {
        while (true) {
            try {//获取包头数据
                int len = is.read(head, headLen, 8 - headLen);
                //判断包头数据是否完整
                headLen += len;//记录包头长度
                if (headLen == 8) {
                    int packetLen = head[1] << 8 | head[0];
                    LogUtil.e("包长度:" + packetLen);
                    headLen = 0;

                    //读取包体数据
                    byte[] body = new byte[packetLen];
                    int bodyLen = 0;
                    while (true) {
                        int recBodyLen = is.read(body, bodyLen, packetLen - bodyLen - 8);
                        bodyLen += recBodyLen;
                        //得到完整包
                        if (bodyLen == (packetLen - 8)) {
                            //解析数据
                            UnPacket unPacket = new UnPacket(head, body);
                            unPacket.Parser();
                            break;
                        }
                    }
                } else {
                    LogUtil.e("包头不够继续接收");
                }
            } catch (IOException e) {
                break;
            }
        }

    }

    /**
     * 处理数据
     *
     * @param packageList
     */
    private void handingData(ArrayList<PackageBean> packageList) {
        if (packageList.size() != 0) {
            LogUtil.e("PackageSize = " + packageList.size());
            StringBuffer stringBuffer = new StringBuffer();
            for (PackageBean packageBean : packageList) {
                byte[] body = packageBean.getBody();
                String sBody = new String(body);
                stringBuffer.append(sBody);
            }
            String s = stringBuffer.toString();
            byte[] bytes = s.getBytes();
            byte[] decode = Base64.decode(bytes, Base64.DEFAULT);
            mJson = new String(decode);
            LogUtil.e("" + mJson);

        }
    }

    /**
     * 读取流
     *
     * @param is
     */

    private void newMethod(InputStream is) {
        bytesHead = new byte[8];
        // 第几个包
        while (!isStop) {
            try {
                HeadBean headBean = handlingHead(bytesHead);
                byte[] byteBody = new byte[headBean.getLength() - 8];
                is.read(byteBody);
                PackageBean packageBean = new PackageBean();
                packageBean.setHeadBean(headBean);
                packageBean.setBody(byteBody);
                if (headBean.getMsgType() == MsgId.MSG_GET_ALL_LIST) {
                    packageList.add(packageBean);
                }
                if (packageList.size() == headBean.getNumAll() &&
                        headBean.getNumCurrent() != 0 &&
                        headBean.getNumCurrent() == headBean.getNumAll()) {
                    isStop = true;
                    LogUtil.e("--Stop--");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理包头
     *
     * @param
     */
    private HeadBean handlingHead(byte[] bytesHead) throws IOException {
        is.read(bytesHead);
        byteBuffer.clear();
        byteBuffer.put(bytesHead, 0, bytesHead.length);
        byteBuffer.position(0);
        HeadBean headBean = new HeadBean();
        short packageSize = byteBuffer.getShort();
        short packageInstruction = byteBuffer.getShort();
        short packageType = byteBuffer.getShort();
        short packageOrderNum = byteBuffer.getShort();
        int packageOrderNum1 = packageOrderNum;
        LogUtil.e("packageOrderNum1 = " + packageOrderNum1);
        int numCurrent = packageOrderNum1 & 0x00ff;
        int numAll = packageOrderNum1 >> 8;
        LogUtil.e("当前是第" + numCurrent + "包");
        LogUtil.e("packageType =" + packageType + "包");
        LogUtil.e("总共是" + numAll + "包");
        headBean.setLength(packageSize);
        headBean.setTypeInstruction(packageInstruction);
        headBean.setMsgType(packageType);
        headBean.setPackageOrderNum(packageOrderNum);
        headBean.setCurrentNum(numCurrent);
        headBean.setAllNum(numAll);
        return headBean;
    }

//    private void getOsData(ByteArrayOutputStream outStream) {
//        byte[] bytes = outStream.toByteArray();
//        int length1 = bytes.length;
//        LogUtil.e("length = " + length1);
//        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bytes.length);
//        byteBuffer.put(bytes, 0, bytes.length);
//        byteBuffer.position(0);
//        HashMap<Integer, PackageBean> map = new HashMap<>();
//        int mapIndex = 0;
//        short packageSize = byteBuffer.getShort();
//        short packageInstruction = byteBuffer.getShort();
//        short packageType = byteBuffer.getShort();
//        short packageOrderNum = byteBuffer.getShort();
//        while () {
//            int p = packageOrderNum;
//            int b = p & 0x00ff;
//            int c = p >> 8;
//            LogUtil.e("当前是第" + b + "包");
//            LogUtil.e("总共是" + c + "包");
//            PackageBean packageBean = new PackageBean();
//            HeadBean headBean = new HeadBean();
//            headBean.setLength(packageSize);
//            headBean.setTypeInstruction(packageInstruction);
//            headBean.setMsgType(packageType);
//            headBean.setPackageOrderNum(packageOrderNum);
//            packageBean.setHeadBean(headBean);
//            byte body = byteBuffer.get(packageSize - 8);
//            packageBean.setBody(body);
//            map.put(mapIndex, packageBean);
////                if (b == c) {
////                    flag = true;
////                }
//            mapIndex++;
//        }
//    }


    private boolean getData(byte[] buffer, int length) throws IOException {
//        String s1 = new String(buffer);
//        stringBuffer.append(s1);
//        String s = byteBuffer.toString();
//        LogUtil.e("---" + s);

        byteBuffer.put(buffer, 0, length);
        byteBuffer.position(0);
        mLength += length;
        if (mLength >= 8) {
            short packageSize = byteBuffer.getShort();
            short packageInstruction = byteBuffer.getShort();
            short packageType = byteBuffer.getShort();
            short packageOrderNum = byteBuffer.getShort();
            int i = packageOrderNum;
            int b = i & 0x00ff;
            int c = i >> 8;
            LogUtil.e("当前是第" + b + "包");
            LogUtil.e("总共是" + c + "包");
//            packageBean = new PackageBean();
//            HeadBean headBean = new HeadBean();
//            headBean.setLength(packageSize);
//            headBean.setTypeInstruction(packageInstruction);
//            headBean.setMsgType(packageType);
//            headBean.setPackageOrderNum(packageOrderNum);
//            packageBean.setHeadBean(headBean);

            short bodySize = (short) (packageSize - 8);
            if (packageSize <= mLength) {
                byte[] body = new byte[bodySize];
                byteBuffer.get(body);
                byte[] decode = Base64.decode(body, Base64.DEFAULT);
                mJson = new String(decode);
                packageBean.setBodyJson(mJson);
                LogUtil.e("received-json:" + mJson);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onEvent(IEvent iEvent) {
        return false;
    }
}
